package com.unism.unisdk.core.transport.action.http;

import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.io.FileUtils;

import com.ning.http.client.AsyncCompletionHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Request;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.Response;
import com.ning.http.client.multipart.ByteArrayPart;
import com.ning.http.client.multipart.Part;
import com.unism.unisdk.common.enumObj.HttpMethod;
import com.unism.unisdk.common.enumObj.MimeType;
import com.unism.unisdk.core.transport.OpenResponse;
import com.unism.unisdk.core.transport.OpenResponseCallback;
import com.unism.unisdk.core.utils.HttpConstant;
/**
 * http 
 * @author liuc
 */
public class HttpAction {
	/**
	 * 
	 * @param callback 回调接口，用于处理response
	 * @param asyncHttpClient  异步io的http请求对象
	 * @param requestId  唯一标识的请求id
	 * @param requestTimeout  请求超时时间
	 * @param httpMethod 当前http请求的方法
	 * @param url  http请求的url
	 * @param request
	 * @return
	 */
	public static OpenResponse httpRequest(final OpenResponseCallback callback, AsyncHttpClient asyncHttpClient,
			String requestId, Integer requestTimeout, HttpMethod httpMethod, 
			           String url, String body,HashMap<String,String> header,
			                       String finalPostFileKey, File finalPostFile) {
		final OpenResponse openResponse = new OpenResponse();
		try {
			RequestBuilder requestBuilder = new RequestBuilder();
			requestBuilder.setRequestTimeout(requestTimeout);
			requestBuilder.setHeader("reqId", requestId);
			
			setStatusLine(requestBuilder,url,httpMethod);
			setRequestHeader(requestBuilder,header);
			setRequestBody(requestBuilder,body,finalPostFileKey,finalPostFile);
           
			Request request = requestBuilder.build();

			if (callback == null) {
				Response response = (Response) asyncHttpClient.executeRequest(request).get();
				openResponse.setHttpCode(response.getStatusCode());
				openResponse.setResult(response.getResponseBody("utf-8"));
			} else {
				asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Object>() {
					public void onThrowable(Throwable t) {
						openResponse.setThrowable(t);
						callback.onCallBack(openResponse);
					}
					public Void onCompleted(Response response) throws Exception {
						openResponse.setHttpCode(response.getStatusCode());
						openResponse.setResult(response.getResponseBody("utf-8"));
						callback.onCallBack(openResponse);
						return null;
					}
				});
			}
		} catch (Throwable e) {
			openResponse.setThrowable(e);
		}
		return openResponse;
	}
	public static void main(String[] args) {
		HttpAction.httpRequest(null, new AsyncHttpClient(),"1111111111", 0, HttpMethod.GET,"https://oapi.dingtalk.com/gettoken?corpid=ding9b5476b29d2f042035c2f4657eb6378f&corpsecret=tH0g0vhVG3R9wKeSZTUu0YzCw_Z28cOOQpevHBtYkyitnKZ0O1m854nZTRuH1mOO", null, null, null, null);
	}
    /**
     * 设置http请求body体
     * @param requestBuilder
     * @param body
     * @param fileKey
     * @param file
     * @throws Exception
     */
	private static void setRequestBody(RequestBuilder requestBuilder, String body,String fileKey, File file) throws Exception{
		// TODO Auto-generated method stub
		requestBuilder.setBodyEncoding("utf-8");
		if(body!=null && !body.trim().equals("")){
			requestBuilder.setBody(body.toString());
		}else{
			if(fileKey!=null && file!=null && !fileKey.trim().equals("")){
				requestBuilder.setMethod(HttpMethod.POST.getName());
				Part part = new ByteArrayPart("media", FileUtils.readFileToByteArray(file),MimeType.multipart_form_data.getName(),
						Charset.forName("utf-8"), file.getName());
				requestBuilder.addBodyPart(part);
			}
		}
	}
    /**
     * 设置http请求头信息
     * @param requestBuilder
     * @param header
     * @throws Exception
     */
	private static void setRequestHeader(RequestBuilder requestBuilder, HashMap<String, String> header) throws Exception{
		// TODO Auto-generated method stub
		if(header!=null){
			Iterator<Entry<String, String>> iter = header.entrySet().iterator();
			while(iter.hasNext()){
				Map.Entry entry = (Map.Entry) iter.next();
				Object key = entry.getKey();
				Object val = entry.getValue();
				requestBuilder.setHeader(key.toString(), val.toString());
			}
			if(!header.containsKey(HttpConstant.CONTENT_TYPE) && !header.containsKey(HttpConstant.CONTENT_TYPE.toLowerCase()) && 
					!header.containsKey(HttpConstant.CONTENT_TYPE.toUpperCase())){
				
				requestBuilder.setHeader(HttpConstant.CONTENT_TYPE, MimeType.application_json.getName());
			}
		}else{
			requestBuilder.setHeader(HttpConstant.CONTENT_TYPE, MimeType.application_json.getName());
		}
	}
    /**
     * 设置http状态行
     * @param requestBuilder
     * @param url
     * @param httpMethod
     * @throws Exception
     */
	private static void setStatusLine(RequestBuilder requestBuilder, String url, HttpMethod httpMethod) throws Exception {
		// TODO Auto-generated method stub
		requestBuilder.setUrl(url);
		if(httpMethod!=null){
			System.out.println(httpMethod.getName());
			requestBuilder.setMethod(httpMethod.getName());
		}else{
			throw new Exception("http method未指定");
		}
	}
}
